package com.xinchao.job.task;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xinchao.common.vo.WeatherVO;
import com.xinchao.core.config.DefaultWeatherCityConfig;
import com.xinchao.job.service.WeatherService;


/**
 * @ClassName GrabWeatherInfoJob
 * @Description 每天定时抓取天气信息
 * @Author HanQinrui
 * @Date 2018/9/4 16:55
 * @Version 1.0
 **/
@DisallowConcurrentExecution
public class GrabWeatherInfoJob extends QuartzJobBean {
    private static Logger logger = LoggerFactory.getLogger(GrabWeatherInfoJob.class);
    @Autowired
    private WeatherService weatherService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        logger.info("执行抓取天气信息【GrabWeatherInfoJob】" );
        try {
            // 获取当前需要抓取天气的城市
            List<HashMap<String, String>> weatherCityList = DefaultWeatherCityConfig.weatherCityList;
            if(!weatherCityList.isEmpty()) {
                for(int i = 0 ; i < weatherCityList.size(); i++) {
                    String cityName = weatherCityList.get(i).get("cityName");
                    WeatherVO weatherBean = new WeatherVO();
                    String tempHigh = null;
                    String tempLow = null;
                    String weatherType = null;
                    String wendu = null;
                    String airPm = null;
                    String airQuality = null;
                    // 此处休眠3秒，是因为该接口每次请求间隔必须3秒一次，如果多次超过3秒内调用多次，会封掉IP段
                    // 每个IP日调用额度2000次，超过过多，会封掉IP段
                    // 关于该接口的问题，联系QQ：8446666
                    if(i > 0) {
                        Thread.sleep(3000);
                    }
                    // 参数url化
                    String city = java.net.URLEncoder.encode(cityName, "utf-8");
                    //拼地址
                    String apiUrl = String.format("https://www.sojson.com/open/api/weather/json.shtml?city=%s",city);
                    //开始请求
                    URL url= new URL(apiUrl);
                    URLConnection open = url.openConnection();
                    InputStream input = open.getInputStream();
                    //转换为String
                    String result = IOUtils.toString(input,"utf-8");
                    //String result = "{\"date\":\"20180913\",\"message\":\"Success !\",\"status\":200,\"city\":\"上海市\",\"count\":22,\"data\":{\"shidu\":\"74%\",\"pm25\":17.0,\"pm10\":24.0,\"quality\":\"优\",\"wendu\":\"28\",\"ganmao\":\"各类人群可自由活动\",\"yesterday\":{\"date\":\"12日星期三\",\"sunrise\":\"05:35\",\"high\":\"高温 28.0℃\",\"low\":\"低温 25.0℃\",\"sunset\":\"18:05\",\"aqi\":27.0,\"fx\":\"东北风\",\"fl\":\"<3级\",\"type\":\"小雨\",\"notice\":\"雨虽小，注意保暖别感冒\"},\"forecast\":[{\"date\":\"13日星期四\",\"sunrise\":\"05:36\",\"high\":\"高温 29.0℃\",\"low\":\"低温 24.0℃\",\"sunset\":\"18:04\",\"aqi\":48.0,\"fx\":\"北风\",\"fl\":\"<3级\",\"type\":\"小雨\",\"notice\":\"雨虽小，注意保暖别感冒\"},{\"date\":\"14日星期五\",\"sunrise\":\"05:36\",\"high\":\"高温 31.0℃\",\"low\":\"低温 25.0℃\",\"sunset\":\"18:03\",\"aqi\":74.0,\"fx\":\"东北风\",\"fl\":\"<3级\",\"type\":\"多云\",\"notice\":\"阴晴之间，谨防紫外线侵扰\"},{\"date\":\"15日星期六\",\"sunrise\":\"05:37\",\"high\":\"高温 32.0℃\",\"low\":\"低温 26.0℃\",\"sunset\":\"18:01\",\"aqi\":69.0,\"fx\":\"东北风\",\"fl\":\"<3级\",\"type\":\"多云\",\"notice\":\"阴晴之间，谨防紫外线侵扰\"},{\"date\":\"16日星期日\",\"sunrise\":\"05:37\",\"high\":\"高温 30.0℃\",\"low\":\"低温 24.0℃\",\"sunset\":\"18:00\",\"aqi\":56.0,\"fx\":\"东北风\",\"fl\":\"<3级\",\"type\":\"小雨\",\"notice\":\"雨虽小，注意保暖别感冒\"},{\"date\":\"17日星期一\",\"sunrise\":\"05:38\",\"high\":\"高温 28.0℃\",\"low\":\"低温 24.0℃\",\"sunset\":\"17:59\",\"aqi\":42.0,\"fx\":\"东南风\",\"fl\":\"<3级\",\"type\":\"中雨\",\"notice\":\"记得随身携带雨伞哦\"}]}}";
                    //输出
                    System.out.println(result);
                    JSONObject jsonObject = JSON.parseObject(result);
                    String status = jsonObject.getString("status");
                    if(!StringUtils.isEmpty(result)) {
                        if("200".equals(status)) {
                            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                            airPm = jsonObject1.getString("pm25");
                            airQuality = jsonObject1.getString("quality");
                            wendu = jsonObject1.getString("wendu");
                            JSONArray jsonArray = jsonObject1.getJSONArray("forecast");
                            JSONObject forecastObj = jsonArray.getJSONObject(0);
                            tempHigh = forecastObj.getString("high");
                            tempLow = forecastObj.getString("low");
                            weatherType = forecastObj.getString("type");
                            weatherBean.setCityName(cityName);
                            weatherBean.setTempHigh(tempHigh);
                            weatherBean.setTempLow(tempLow);
                            weatherBean.setWeatherType(weatherType);
                            weatherBean.setWendu(wendu);
                            weatherBean.setAirPM(airPm);
                            weatherBean.setAirQuality(airQuality);
                            // 保存天气信息
                            weatherService.insertWeather(weatherBean);
                        }
                    }
                }
            }
            stopWatch.stop();
            logger.info("【GrabWeatherInfoJob】执行完毕，执行时间："+stopWatch.getTotalTimeSeconds());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("【GrabWeatherInfoJob】执行完毕，失败：" + e.toString());
        }
    }
}
